<?php

declare(strict_types=1);

namespace app\common\model;

use think\facade\Db;
use think\Model;
use think\model\concern\SoftDelete;
use think\facade\Session;

class AdminAdmin extends Model
{
    use SoftDelete;
    //根据区服ID和玩家ID获取玩家信息
    public static function getPlayerById($server_id, $player_id) {
        // 提取后三位数字作为数据库编号
        $database_suffix = substr($server_id, -3);

        // 拼接数据库名称
        $database_name = "h5_cq_{$database_suffix}";

        // 将 $player_id 转义以防止 SQL 注入攻击
        $escaped_player_id = addslashes($player_id);

        // SQL查询语句
        $sql = "SELECT actorid, actorname FROM `{$database_name}`.`actors` WHERE `accountname` = '{$escaped_player_id}'";
//        $sql = "SELECT actorid,actorname FROM `h5_cq_003`.`actors` WHERE `accountname` = 'yaonie';";  //调试

        // 执行查询并返回结果
        return Db::query($sql);
    }



    //获取物品列表
    public static function getItemList(){
        // 读取服务器目录中的 item.txt 文件
        $filePath = '/www/wwwroot/wch123.com/admin/item.txt';
        $items = [];

        if (file_exists($filePath)) {
            $file = fopen($filePath, 'r');
            while (!feof($file)) {
                $line = fgets($file);
                if ($line !== false) {
                    $txts = explode(';', $line);
                    if (count($txts) >= 2) {
                        $items[] = [
                            'value' => trim($txts[0]),
                            'name' => trim($txts[1])
                        ];
                    }
                }
            }
            fclose($file);
        }
        return $items;
    }

    // 获取服务器列表
    public static function getServerList(){
        $sql = "select * from `h5`.`h5_server` order by sid ASC";
        return  Db::query($sql);
    }
    


    // 获取列表
    public static function getList()
    {
        $where = [];
        $limit = input('get.limit');

        if ($search = input('get.username')) {
            $where[] = ['username', 'like', "%" . $search . "%"];
        }
        if ($search = input('get.rlink')) {
            $where[] = ['rlink', 'like', "%" . $search . "%"];
        }
        $list = self::order('id', 'desc')
            ->where('id', '<>', Session::get('admin.id'))
            ->where('id', '>', '1')
            ->withoutField('password,token,delete_time')
            ->where($where)
            ->paginate($limit);
        return ['code' => 0, 'data' => $list->items(), 'extend' => ['count' => $list->total(), 'limit' => $limit]];
    }

    // 获取数据
    public static function getConst()
    {
        $where = '';

        if (Session::get('admin.id') != '1') {
            $where  .= 'where  a.id' . '=' . ' ' . Session::get('admin.id');
        }
        //所有订单数 所有充值金额  今日充值金额  今日订单数
        $item_count = Db::query("SELECT
                                IFNULL(SUM(CASE WHEN c.`status` = 1 THEN 1 ELSE 0 END), 0) AS total_count, 
                                IFNULL(SUM(CASE WHEN c.`status` = 1 THEN c.jine ELSE 0 END), 0) AS total_jine, 
                                IFNULL(SUM(CASE WHEN c.`status` = 1 AND DATE(c.cztime) = CURDATE() THEN c.jine ELSE 0 END), 0) AS today_jine,
                                IFNULL(SUM(CASE WHEN c.`status` = 1 AND DATE(c.cztime) = CURDATE() THEN 1 ELSE 0 END), 0) AS today_count
                                FROM
                                    admin_admin a 
                                RIGHT JOIN
                                    gm_tglogs b ON a.rlink = b.acode 
                                RIGHT JOIN
                                    gm_tgczlogs c ON c.actorname = b.baccount 
                                " . $where);
        return [
            'total_count' => !empty($item_count) ? $item_count[0]['total_count'] : 0,
            'total_jine' => !empty($item_count) ? $item_count[0]['total_jine'] : 0,
            'today_jine' => !empty($item_count) ? $item_count[0]['today_jine'] : 0,
            'today_count' => !empty($item_count) ? $item_count[0]['today_count'] : 0
        ];
    }


    // 获取用户下拉
    public static function getSelect()
    {
        return Db::table('gmpre.admin_admin')->order('id')->field('id,username,rlink,nickname')->select(); // 直接返回结果数组，不要包装在 ['code'=>0,'data'=>...] 中
    }
    // 获取物品列表下拉
    public static function getServerLsSelect()
    {
        return Db::table('h5.h5_server')->order('sid')->field('id,sid,name')->select();
    }

    public static function getMaxServerId()
    {
        $sql = "select MAX(id) as id from `h5`.`h5_server` ";
        return Db::query($sql)[0]['id'];
    }

    //获取游戏服跨服id
    public static function getsrvid($sid)
    {
        $sql = "SELECT srvid FROM kf.crossroute WHERE :sid BETWEEN start_id AND end_id ORDER BY srvid DESC LIMIT 1";
        $result = Db::query($sql, ['sid' => $sid]);
        if (!empty($result)) {
            $filename = intval($result[0]['srvid']) - 10000;
            return $filename;
        } else {
            return null;
        }
    }

    // 获取服务器列表下拉
    public static function getItemLsSelect()
    {
        return Db::table('gmpre.gm_items')->field('itemid,itemname,itemimg')->select();
    }

    // 获取预设物品下拉
    public static function getGoodsSelect()
    {
        return Db::table('gmpre.gm_sendgoodsgls')->where('isenable=1')->field('id,sendname,sendgoodsls')->select();
    }

    // 获取服务器列表合区后的下拉
    public static function getServerLsHeQuSelect()
    {
        $sql = "SELECT 
                    CASE 
                        WHEN COUNT(*) = 1 THEN MIN(id)
                        ELSE CONCAT(MIN(id), '-', MAX(id))
                    END AS name,
                    sid AS serverid
                FROM h5_server
                GROUP BY FLOOR((id - 1) / 8), sid";

        return Db::query($sql);
    }

    // 修改区服名称
    public static function MoServerName($id, $servername, $name)
    {
        preg_match("/【(.*?)】/", $name, $matches);
        $newServername = $servername . '【' . $matches[1] . '】';
        $sql = "UPDATE  h5.h5_server SET name='$newServername' WHERE id=$id;";
        Db::execute($sql);
    }

    // 修改玩家密码
    public static function MoPalyerPwd($serverid, $actorname, $password)
    {
        $newpassword = md5(trim($password));
        $newserverid = self::getDBName($serverid);

        $sql1 = "UPDATE `h5`.`account` SET `pass` = '$newpassword' WHERE `account` = '$actorname';";
        $sql2 = "UPDATE $newserverid.`globaluser` SET `passwd` = '$newpassword' WHERE `account` = '$actorname';";

        Db::execute($sql1);
        Db::execute($sql2);
    }

    // 修改玩家职业
    public static function MoPalyerJob($serverid, $actorname, $newJob)
    {
        $newserverid = self::getDBName($serverid);
        $sql = "UPDATE $newserverid.`actors` SET `job` = '$newJob' WHERE `accountname` = '$actorname';";
        Db::execute($sql);
    }

    // 根据区服和账号获取角色名 
    public static function getqueryuname($actorname, $serverid)
    {
        $where = [];
        $where[] =  ['accountname', '=', $actorname];
        $newserverid = self::getDBName($serverid);
        return Db::table($newserverid . '.actors')->field('actorid,actorname,job')->where($where)->select();
    }

    // 获取数据库名称 传入$serverid
    public static function getDBName($serverid)
    {
        $newserverid = 'h5_cq_';
        // 使用正则表达式匹配并获取有效的字符
        $integerValue = intval($serverid) - 1000;
        // 如果有匹配到有效字符，则返回匹配结果，否则返回 "0"
        $trimmedString = $integerValue < 0 ? "0" : strval($integerValue);
        if (env('APP_DEBUG')) {
            $newserverid .= '00' . $trimmedString;
        } else {
            $newserverid .= '' . $trimmedString;
        }

        return $newserverid;
    }



    // 获取日志列表
    public static function getLog()
    {
        $where = [];
        $limit = input('get.limit');
        if ($search = input('get.uid')) {
            $where[] =  ['uid', '=', $search];
        }
        $list = AdminAdminLog::with('log')->order('id', 'desc')->where($where)->paginate($limit);
        return ['code' => 0, 'data' => $list->items(), 'extend' => ['count' => $list->total(), 'limit' => $limit]];
    }
    // 管理拥有的角色
    public function roles()
    {
        return $this->belongsToMany('AdminRole', 'admin_admin_role', 'role_id', 'admin_id');
    }

    // 获取管理拥有的角色
    public static function getRole($id)
    {
        $admin = self::with('roles')->where('id', $id)->find();
        $roles = AdminRole::select();
        foreach ($roles as $k => $role) {
            if (isset($admin->roles) && !$admin->roles->isEmpty()) {
                foreach ($admin->roles as $v) {
                    if ($role['id'] == $v['id']) {
                        $roles[$k]['own'] = true;
                    }
                }
            }
        }
        return ['admin' => $admin, 'roles' => $roles];
    }

    // 获取用户直接权限
    public static function getPermission($id)
    {
        $admin = self::with('directPermissions')->find($id);
        $permissions = AdminPermission::order('sort', 'asc')->select();
        foreach ($permissions as $permission) {
            foreach ($admin->direct_permissions as $v) {
                if ($permission->id == $v['id']) {
                    $permission->own = true;
                }
            }
        }
        $permissions = get_tree($permissions->toArray());
        return ['admin' => $admin, 'permissions' => $permissions];
    }


    // 管理的直接权限
    public function directPermissions()
    {
        return $this->belongsToMany('AdminPermission', 'admin_admin_permission', 'permission_id', 'admin_id');
    }

    // 用户的所有权限
    public static function permissions($id, $root)
    {
        $admin = self::with(['roles.permissions', 'directPermissions'])->findOrEmpty($id)->toArray();
        $permissions = [];
        //超级管理员缓存所有权限
        if ($admin['id'] == 1) {
            $perms = AdminPermission::order('sort', 'asc')->select()->toArray();
            foreach ($perms as $p) {
                if ($p['status'] == 1) {
                    $permissions[$p['id']] =  $p;
                    $permissions[$p['id']]['href'] = is_url($p['href']) ?? $root . $p['href'];
                }
            }
            if (env('APP_DEBUG') == true) {
                $permissions[0] = [
                    "id" => -1,
                    "pid" => 0,
                    "title" => "自动生成",
                    "icon" => "layui-icon layui-icon-util",
                    "type" => 0,
                    "href" => "",
                ];
                $permissions[-1] = [
                    "id" => -2,
                    "pid" => -1,
                    "title" => "CRUD管理",
                    "icon" => "layui-icon layui-icon-console",
                    "type" => 1,
                    "openType" => "_iframe",
                    'href' => $root . "/crud/index",
                ];
            }
        } else {
            //处理角色权限
            if (isset($admin['roles']) && !empty($admin['roles'])) {
                foreach ($admin['roles'] as $r) {
                    if (isset($r['permissions']) && !empty($r['permissions'])) {
                        foreach ($r['permissions'] as $p) {
                            if ($p['status'] == 1) {
                                $permissions[$p['id']] =  $p;
                                $permissions[$p['id']]['href'] = is_url($p['href']) ?? $root . $p['href'];
                            }
                        }
                    }
                }
            }
            //处理直接权限
            if (isset($admin['directPermissions']) && !empty($admin['directPermissions'])) {
                foreach ($admin['directPermissions'] as $p) {
                    if ($p['status'] == 1) {
                        $permissions[$p['id']] =  $p;
                        $permissions[$p['id']]['href'] = is_url($p['href']) ?? $root . $p['href'];
                    }
                }
            }
            $key = array_column($permissions, 'sort');
            array_multisort($key, SORT_ASC, $permissions);
        }
        //合并权限为用户的最终权限
        return $permissions;
    }
}
